/*
 * @Descripttion:
 * @version:
 * @Author: sunye
 * @Date: 2025-04-01 00:14:28
 * @LastEditors: sunye
 * @LastEditTime: 2025-04-14 00:12:22
 */
import { createRouter, createWebHistory } from 'vue-router'
// import routes from '@/router/routes'
import routes from '@/router/routes'
import { useUserStore } from '@/store/user'
// 引入pinia
import pinia from '../store'

const userStore = useUserStore(pinia)

// 进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
//右侧进度条加载中loding状态去除
nprogress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    }
  },
})
// 路由鉴权
router.beforeEach(async (to, from, next) => {
  console.log(to, from);
  const token = userStore.token;
  nprogress.start()
  if (token) {
    // 是否已经获取用户信息
    if (userStore.username) {
      next()
    } else {
      // 获取用户信息
      await userStore.getUserInfo()
      next({
        path: '/login', query: {
          redirect: to.path
        }
      })
    }
  } else {
    if (to.path === '/login') {
      // 用户未登录
      next()
    } else {
      next({
        path: '/login', query: {
          redirect: to.path
        }
      })
    }
  }
})

router.afterEach((to, from) => {
  console.log(to, from);
  nprogress.done();
})

export default router
